package com.kenyi.co.ui.me.ui;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnNetWorkErrorListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.kenyi.co.MainActivity;
import com.kenyi.co.R;
import com.kenyi.co.common.ui.BaseActivity;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.ui.me.adapter.MainFavAdapter;
import com.kenyi.co.ui.me.bean.UserFavBean;
import com.kenyi.co.ui.me.bean.UserFavSettingBean;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.kenyi.co.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


/**
 * 获取偏好
 */
public class MeFavActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MeFavActivity";

    private Button li_footer;


    private List<UserFavBean.DatasBean> itemList;
    private int pos = 0;
    private int selectnum = 0;
    private TextView tv_home_title;

    private Toolbar toolbar;
    private LRecyclerView mRecyclerView = null;
    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
    private MainFavAdapter mDataAdapter = null;
    private UserFavBean packlist;
    private RelativeLayout top;
    private String isfinish = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fav_me);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null && bundle.containsKey("isfinish")) {
            isfinish = bundle.getString("isfinish");

        }
        initView();
        mRecyclerView = (LRecyclerView) findViewById(R.id.list);
        mDataAdapter = new MainFavAdapter(MeFavActivity.this);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能
        mRecyclerView.setLoadMoreEnabled(false);
        mRecyclerView.setPullRefreshEnabled(false);

        mRecyclerView.setOnNetWorkErrorListener(new OnNetWorkErrorListener() {
            @Override
            public void reload() {

            }
        });
        mRecyclerView.refresh();

        LinearLayout adView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.activity_me_footer, null);
        li_footer = adView.findViewById(R.id.bt_summit);
        li_footer.setText("选好了");
        li_footer.setOnClickListener(this);
        li_footer.setVisibility(View.GONE);
        mLRecyclerViewAdapter.addFooterView(adView);
        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                UserFavBean.DatasBean item = mDataAdapter.getDataList().get(position);
                selectnum = 0;
                if (item.isSelected()) {

                    item.setSelected(false);
                } else {
                    for (int i = 0; i < itemList.size(); i++) {
                        if (itemList.get(i).isSelected()) {
                            selectnum++;
                        }

                    }
                    if (selectnum < 3) {
                        item.setSelected(true);
                    } else {
                        ToastUtil.showShort(getApplicationContext(), "最多选择3个！");
                    }

                }

                mLRecyclerViewAdapter.notifyDataSetChanged();
            }
        });
        getFav();
    }

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));//设置状态栏颜色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        }
    }

    private void initView() {
        setStatusBar();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        top = findViewById(R.id.top);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_home_title = (TextView) findViewById(R.id.tv_home_title);
        tv_home_title.setText("偏好设置");
        if ("1".equals(isfinish)) {
            top.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        MobclickAgent.onPageStart("个人头像");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        MobclickAgent.onPageEnd("个人头像");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.bt_summit:
                List<String> itemList2 = new ArrayList<String>();
                String tags = "";
                for (int i = 0; i < itemList.size(); i++) {
                    if (itemList.get(i).isSelected()) {
                        itemList2.add(itemList.get(i).getName());
                    }
                }
                if (itemList2.size() == 0) {
                    ToastUtil.showShort(getApplicationContext(), "请选择偏好！");
                    return;
                }
//                for (int i = 0; i < itemList2.size(); i++) {
//                    if (i == 0) {
//                        tags = itemList.get(i).getName();
//                    }
//                    if (i == 1) {
//                        tags = tags + "|" + itemList.get(i).getName();
//                    }
//                    if (i == 2) {
//                        tags = tags + "|" + itemList.get(i).getName();
//                    }
//                }
                itemList2.toArray();
                if ("1".equals(isfinish)) {
                    SharepUtils.setShDataList(MeFavActivity.this, SharepUtils.USER_FAV_TAGS_LIST, itemList2);
                    SharepUtils.setString_info(MeFavActivity.this, "1", SharepUtils.USER_LOGIN_ONE);
                    Intent intent2 = new Intent();
                    intent2.setClass(MeFavActivity.this, MainActivity.class);
                    startActivity(intent2);
                    finish();
                } else {
                    setFav(itemList2);
                }
                break;
        }
    }

    /**
     * 获取偏好
     */
    public void getFav() {

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", SharepUtils.getString_info(MeFavActivity.this, SharepUtils.USER_LOGIN_TOKEN));

        String url = NetConfig.APPUSER_GETFAV;

        OkHttpUtils.get()
                .url(url)

                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                        mRecyclerView.refreshComplete(10);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        int num = 0;
                        packlist = gson.fromJson(response, UserFavBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
                            itemList = new ArrayList<UserFavBean.DatasBean>();
                            itemList = packlist.getDatas();
                            num = itemList.size();
                            mDataAdapter.addAll(itemList);
                            mRecyclerView.setVisibility(View.VISIBLE);
                            mRecyclerView.refreshComplete(num);
                            li_footer.setVisibility(View.VISIBLE);
                        }


                    }
                });
    }

    /**
     * 修改头像
     */
    public void setFav(List<String> itemList2) {

        Gson gson = new Gson();
        Map<Object, Object> map = new HashMap<>();
        map.put("userId", SharepUtils.getString_info(MeFavActivity.this, SharepUtils.USER_LOGIN_USERID));
        map.put("likeTags", itemList2);
        String str = gson.toJson(map);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", SharepUtils.getString_info(MeFavActivity.this, SharepUtils.USER_LOGIN_TOKEN));


        String url = NetConfig.APPUSER_SETFAV;

        OkHttpUtils.postString()
                .url(url)
                .content(str)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        UserFavSettingBean packlist = gson.fromJson(response, UserFavSettingBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
                            List<String> LikeTags = packlist.getDatas();
                            if (LikeTags != null && LikeTags.size() > 0) {
                                SharepUtils.setShDataList(MeFavActivity.this, SharepUtils.USER_FAV_TAGS_LIST, LikeTags);
                            }
                            finish();
                        }


                    }
                });
    }


}
